#include "VZManager.h"

void VZManager::onStart()
{
}

void VZManager::onUnitRecieved(Unit *unit)
{
	int const mineRadius = 500;

	if(units.exists(unit))
		return;
	
	UnitType uType = unit->getType();

	if(uType.isResourceContainer() || uType.isResourceDepot() && unit->getPosition().isValid()) {
		// see if it can belong to an existing group
		bool added = false;
		for(int i = 0; i < placer.vitalZones.size(); i++) {
			Position vect = unit->getPosition() - placer.vitalZones[i].getCentroid();
			int dist = (int)sqrt(pow((double)vect.x,2) + pow((double)vect.y,2));
			if(dist < mineRadius) {
				placer.vitalZones[i].addPoint(unit->getPosition());
				added = true;
			}
		}
		if(added) {
			units.insert(unit);
			return;
		}

		VitalZone newZone;
		// add resources and command centers in the mineRadius
		Unitset newUnits = unit->getUnitsInRadius(mineRadius);
		for(Unitset::iterator i = newUnits.begin(); i != newUnits.end(); ++i) {
			Position pos = i->getPosition();
			if((i->getType().isResourceDepot() || i->getType().isResourceContainer()) && pos.isValid() && i->isVisible()) {
				units.insert(*i);
				newZone.addPoint(pos);
			}
		}
		placer.addVitalZone(newZone, Colors::Blue);
	}
}

void VZManager::think()
{
	for(int j = 0; j < placer.vitalZones.size(); j++) {
		std::vector<Position> *polygon = placer.vitalZones[j].getPolygon();
		if(polygon == NULL || polygon->size() < 3)
			continue;
		Broodwar->drawDotMap(placer.vitalZones[j].getCentroid(), Colors::Red);
		for(int i = 0; i < polygon->size() - 1; i++) {
			Broodwar->drawLineMap((*polygon)[i], (*polygon)[i+1], Colors::Blue);
			//Broodwar->drawTextMap((*polygon)[i].x, (*polygon)[i].y, "%f", atan2((double)(*polygon)[i].x, (*polygon)[i].y));
		}
		Broodwar->drawLineMap((*polygon)[0], (*polygon)[polygon->size() - 1], Colors::Blue);
	}
}